/*
 * Copyright 2012 the original author or authors.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */
package org.chacha.dao;

import java.util.ArrayList;
import java.util.List;

import org.chacha.model.Account;

import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.QueryBuilder;
import com.mongodb.WriteConcern;


/**
 * 
 *	@author: hejing
 *	@date: 2012-11-5-下午02:20:21
 */
public class AccountDAO extends AbstractDAO implements DAO{
	private static final String COLLECTION_ACCOUNT="account";
	
	static{
		//创建索引，无就创建，有忽略
		DBCollection coll=connection.getCollection(COLLECTION_ACCOUNT);
		coll.ensureIndex(new BasicDBObject("userName",1), "idx_name",true);
	}
	
	public AccountDAO() {
		super();
	}
	@Override
	public String getCollectionName(){
		return COLLECTION_ACCOUNT;
	}
	
	/**
	 * 通过_id查询帐号
	 * @param id  _id
	 * @return
	 */
	public Account getAccountByID(String id){
		DBCollection coll=connection.getCollection(COLLECTION_ACCOUNT);
        DBObject dbObject = coll.findOne(super.idQuery(id));
        if(dbObject != null) {
        	Account acct=new Account();
        	acct.fromDbObject(dbObject);
            return acct;
        } else {
            return null;
        }
	}
	
	/**
	 * 通过用户名查询帐号
	 * @param userName
	 * @return
	 */
	public Account getAccountByName(String userName){
		DBObject entity=queryUserName(userName);
        if(entity != null) {
        	Account acct=new Account();
        	acct.fromDbObject(entity);
            return acct;
        } else {
            return null;
        }
	}
	
	/**
	 * 增加一个帐号
	 * @param entity
	 * @return 新增帐号实体
	 */
	public Account add(Account entity){
		DBCollection coll=connection.getCollection(COLLECTION_ACCOUNT);
		entity.set_id(super.generateID());
		coll.insert(entity.toDbObject(),WriteConcern.NONE);
		return entity;
	}
	/**
	 * 批量增加帐号
	 * @param entitys
	 * @return
	 */
	public boolean addBatch(Account[] entitys){
		try{
			DBCollection coll=connection.getCollection(COLLECTION_ACCOUNT);
			List<DBObject> acctList=new ArrayList<DBObject>();
			for(Account entity:entitys){
				entity.set_id(super.generateID());
				DBObject o=entity.toDbObject();
				acctList.add(o);
			}
			coll.insert(acctList,WriteConcern.SAFE);
		}catch(Exception e){
			log.error("addBatch:"+e);
			return false;
		}
		return true;
	}
	
	/**
	 * 通过ID删除帐号
	 * @param id
	 */
	public void deleteByID(String id){
		DBCollection coll=connection.getCollection(COLLECTION_ACCOUNT);
		DBObject dbObject = coll.findOne(super.idQuery(id));
		if(dbObject!=null)
			coll.remove(dbObject, WriteConcern.SAFE);
	}
	
	/**
	 * 通过用户名删除帐号
	 * @param userName
	 */
	public void deleteAccount(String userName){
		DBObject entity=queryUserName(userName);
		if(entity!=null){
			DBCollection coll=connection.getCollection(COLLECTION_ACCOUNT);
			coll.remove(entity, WriteConcern.SAFE);
		}
	}
	
	private DBObject queryUserName(String userName){
		DBCollection coll=connection.getCollection(COLLECTION_ACCOUNT);
		QueryBuilder queryBuilder = QueryBuilder.start();
		DBObject query=queryBuilder.put("userName").is(userName).get();
		DBObject entity=coll.findOne(query);
		return entity;
	}
	/**
	 * 根据用户名更新account
	 * @param acct
	 */
	public void updateAccount(Account acct){
		DBCollection coll=connection.getCollection(COLLECTION_ACCOUNT);
		QueryBuilder queryBuilder = QueryBuilder.start();
		DBObject query=queryBuilder.put("userName").is(acct.getUserName()).get();
		coll.setWriteConcern(WriteConcern.SAFE);
		coll.update(query, acct.toDbObject());
	}
	/**
	 * 批量查询帐号
	 * @param nameArray
	 */
	public Account[] getAccounts(String[] nameArray) {
		List<Account> result=new ArrayList<Account>();
		DBCollection coll=connection.getCollection(COLLECTION_ACCOUNT);
		QueryBuilder queryBuilder = QueryBuilder.start();
		DBObject query=queryBuilder.put("userName").in(nameArray).get();
		DBCursor cursor=coll.find(query);
		try{
			while(cursor.hasNext()){
				DBObject obj=cursor.next();
				Account a=new Account();
				a.fromDbObject(obj);
				result.add(a);
			}
		}finally{
			if(cursor!=null)
				cursor.close();
		}
		return (Account[])result.toArray(new Account[0]);
	}

}
